#include <hw/inout.h>
#include <sys/neutrino.h>
#include <stdint.h>
#include "DA.h"
#include <sys/mman.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>

uintptr_t da_lsbHandle;
uintptr_t da_msbHandle;
uintptr_t da_status;


void initDARegister(void)
{
	// Get a handle to the LSB of the A/D register
	da_lsbHandle = mmap_device_io( 1, DA_LSB );


	// Get a handle to the MSB of the A/D register
	da_msbHandle = mmap_device_io( 1, DA_MSB);

	// Get a handle to the analog input status register
	da_status = mmap_device_io( 1, DA_STATUS );



	out8(da_status, DA_RESET);
}

void writeValue(float f) {
	if(f>=10.0) {
		f = 9.99;
	} else if(f<=-10.0) {
		f = -9.9;
	}

	uint16_t intval = (((f/10.0)*2048)+2048);
	uint8_t MSB,LSB;



	//wait for DA to be ready
	while(  (in8(da_status)&DA_BUSY)!=0 ) {
		usleep(AD_WAIT);
	}
	//write lsb, then msb and channel number
	LSB=intval&0xFF;

	MSB=intval/256;

	out8(da_lsbHandle,LSB);
	out8(da_msbHandle,(MSB+(0<<6)) );

	while(  (in8(da_status)&DA_BUSY)!=0 ) {
		usleep(AD_WAIT);
	}
}
